/*
 * Copyright (C) 2013
 * Shopping
 */
package com.mshopping.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Environment;

/**
 * This class is used for ...
 * 
 * @author liuhuan
 * @version 1.0, 2013-9-1 下午7:13:35
 */
public class FileUtil {

	public static String getSdCordPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	public static boolean createFile(String path) {
		File file = new File(path);
		try {
			if (!file.exists()) {
				String dirPath = path.substring(0, path.lastIndexOf("/"));
				if (createDir(dirPath)) {
					return file.createNewFile();
				}
			}
		} catch (Exception e) {
		}
		return false;
	}

	public static boolean createDir(String path) {
		File file = new File(path);
		try {
			if (!file.exists()) {
				file.mkdirs();
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static String fromFile(File f) throws IOException {
		InputStream is = new FileInputStream(f);
		byte[] bs = new byte[is.available()];
		is.read(bs);
		is.close();
		return new String(bs);
	}

	public static void toFile(File f, String s) throws IOException {
		// 只有手机rom有足够的空间才写入本地缓存
		if (CommonUtil.enoughSpaceOnPhone(s.getBytes().length)) {
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(s.getBytes());
			fos.close();
		}
	}
}
